// This file is required by the index.html file and will
// be executed in the renderer process for that window.
// All of the Node.js APIs are available in this process.
const express = require('express');
const app = require('express')();
const http = require('http').Server(app);
const io = require('socket.io')(http);
const path = require('path');

let userList = [];
   
app.use(express.static('assets'));

    io.on('connection', function(socket){      
     
        socket.on('chat message', function(msg){
            // console.log('接受的消息是: ' + msg);
            // io.emit('chat message', msg + '---aaaa');          
            
        });

        socket.on('p2p-in', function (data) {
            console.log('aaa');            
            console.log(data); 
            io.sockets.connected[data.to].emit('p2p-out', data);
        })     
        
        userList.push({
            socketId: socket.id, 
            nick: socket.handshake.query.nick,
            imgId: socket.handshake.query.imgId
        });


        //某个用户退出后，广播通知所有人更新列表
        // console.log(Object.keys(io.sockets.sockets));
        socket.on('disconnect', function (data) {
            console.log('断开了');
            
            // console.log(data);          
            console.log(userList);
            // console.log(io.sockets);
            // console.log(Object.keys(io.sockets.sockets));
            let ids = Object.keys(io.sockets.sockets);
            var temp = [];
            ids.forEach((v) => {
                userList.forEach((user) => {
                    if (v == user.socketId) {
                        temp.push(user);
                    }
                })
            })

            userList = temp;
            io.sockets.emit('user-list', userList);     
            
        });

     

        //群发最新用户列表
        io.sockets.emit('user-list', userList);        
       
    });



    http.listen(9999, () => { 
        console.log('服务器已启动');
        
     });
    


